package com.hengxinguotong.zhihuichengjian.ui.security;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.CompanyListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.CompanyListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.QualityTestActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/13.
 */

public class CompanyListActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView save_Tv;
    @BindView(R.id.company_lv)
    PullToRefreshListView companyLv;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    public static  int FROM = 1; //1 质量检查  2  质量报告、安全报告 3安全检查
     public static  int TYPE = 1; //1 获取公司列表  2  获取班组列表
    private int pageIndex = 1;
    private List<Company> companyList;
    private CompanyListAdapter adapter;
    private CompanyListActivity mActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_list);
        ButterKnife.bind(this);
        mActivity = this;
        companyLv.setMode(PullToRefreshBase.Mode.BOTH);
        setListener();
        switch (CompanyListActivity.TYPE){
            case 1:
                getCompanyList("加载中…");
                titleTv.setText("劳务公司列表");
                break;
            case 2:
                getGroupList("加载中");
                titleTv.setText("班组列表");
                break;
        }

    }

    @OnClick({R.id.iv_back, R.id.save_tv})
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                if(adapter != null){
                    switch (FROM){
                        case 1:
                            switch (TYPE){
                                case 1:
                                    intent = new Intent(this, QualityTestActivity.class);
                                    intent.putExtra("company", adapter.getSelect());
                                    startActivity(intent);
                                    break;
                                case 2:
                                    intent = new Intent(this, QualityTestActivity.class);
                                    intent.putExtra("group", adapter.getSelect());
                                    startActivity(intent);
                                    break;
                            }
                            break;
                        case 2:
                            switch (TYPE){
                                case 1:
                                    intent = new Intent(this, SecurityAccidentActivity.class);
                                    intent.putExtra("company", adapter.getSelect());
                                    startActivity(intent);
                                    break;
                                case 2:
                                    intent = new Intent(this, SecurityAccidentActivity.class);
                                    intent.putExtra("group", adapter.getSelect());
                                    startActivity(intent);
                                    break;
                            }
                            break;
                        case 3:
                            switch (TYPE){
                                case 1:
                                    intent = new Intent(this, SecurityTestActivity.class);
                                    intent.putExtra("company", adapter.getSelect());
                                    startActivity(intent);
                                    break;
                                case 2:
                                    intent = new Intent(this, SecurityTestActivity.class);
                                    intent.putExtra("group", adapter.getSelect());
                                    startActivity(intent);
                                    break;
                            }
                            break;
                    }

                }
                break;
        }
    }

    private void setListener(){
        companyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelect(position - 1);
            }
        });

        companyLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                switch (CompanyListActivity.FROM){
                    case 1:
                        getCompanyList(null);
                        break;
                    case 2:
                        getGroupList(null);
                }

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                switch (CompanyListActivity.FROM){
                    case 1:
                        getCompanyList(null);
                        break;
                    case 2:
                        getGroupList(null);
                }
            }
        });
    }

    private void getCompanyList(String alert){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/projectCompany/queryDetail/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(companyLv.isRefreshing()){
                    companyLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    CompanyListRes companyListRes = gson.fromJson(json, CompanyListRes.class);
                    if(null !=companyListRes.getValue()){
                        companyFilter(companyListRes);
                        process(companyListRes.getValue());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(companyLv.isRefreshing()){
                    companyLv.onRefreshComplete();
                }
                showEmptyView(companyLv);
            }
        });
    }

    /**
     * 过滤租赁公司
     *
     * @param companyListRes
     */
    private void companyFilter(CompanyListRes companyListRes) {
        List<Company> companies = companyListRes.getValue();
        Iterator<Company> companyIterator = companies.iterator();
        while (companyIterator.hasNext()) {
            Company company = companyIterator.next();
            if (company.getType() == 3) {
                companyIterator.remove();
            }
        }
    }

    private void getGroupList(String alert){
        JSONObject jsonObject = new JSONObject();
        try {
            String projectCompanyId = getIntent().getStringExtra("projectCompanyId");
            jsonObject.put("projectCompanyId", projectCompanyId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/team/queryDetail/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(companyLv.isRefreshing()){
                    companyLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    CompanyListRes companyListRes = gson.fromJson(json, CompanyListRes.class);
                    if(null !=companyListRes.getValue()){
                        process(companyListRes.getValue());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(companyLv.isRefreshing()){
                    companyLv.onRefreshComplete();
                }
                showEmptyView(companyLv);
            }
        });
    }

    private void process(List<Company> datas){
        if(pageIndex == 1){
            if(datas.size() == 0){
                showEmptyView(companyLv);
            }else{
                dismissEmptyView();
            }
            companyList = datas;
            adapter = new CompanyListAdapter(companyList, mActivity, TYPE);
            companyLv.setAdapter(adapter);
            if(datas.size() == Utils.ONCECOUNT){
                companyLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }else{
            companyList.addAll(datas);
            adapter.notifyDataSetChanged();
        }

        if(datas.size() < Utils.ONCECOUNT){
            companyLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }
}
